package cn.lcfms.cms.collect;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import org.apache.commons.io.FileUtils;

import cn.lcfms.app.admin.bean.ArticleBean;
import cn.lcfms.bin.core.Application;
import cn.lcfms.bin.service.BaseService;
import cn.lcfms.cms.CollctBase;
import cn.lcfms.cms.Collect;
import cn.lcfms.cms.CollectResult;
import cn.lcfms.utils.TimeUtils;

public class InsertArticle extends CollectResult{

	public InsertArticle(Collect collect) {
		super(collect);
	}

	@Override
	public boolean _do(HashMap<String, String> content) {	
		ArticleBean data=new ArticleBean();
		if(content.containsKey("title")) {
			String title=content.get("title");	
			if(title.length()>60) {
				setMsg(false, "标题过长");	
				return false;
			}
			data.setTitle(title);		
		}
		if(content.containsKey("description")) {
			String description=content.get("description");			
			data.setDesc(description);
		}
		if(content.containsKey("details")) {
			String details=content.get("details");	
			details=getImg(details);
			details=deleteA(details);
			data.setDetails(details);
		}
		if(content.containsKey("labels")) {
			String labels = content.get("labels");
			data.setLabels(labels.split(","));
		}
		if(content.containsKey("itemId")) {
			String itemId = content.get("itemId");
			data.setCategory_id(Integer.valueOf(itemId));
		}
		if(data.getTitle()!=null && data.getDetails()!=null) {
			BaseService service = Application.getService("articles");			
			data.setCreated_at(TimeUtils.getCurrentDateTime());
			service.insert(data);
			int id = service.insert_id();
			String aimg = CollctBase.getAimg();
			if(null!=aimg && !"".equals(aimg)) {
				try {
					byte[] browser = CollctBase.browser(aimg, collect.getBean().getCookie());
					String shortfile = CollctBase.getFileName(aimg);
					String filepath=Application.ROOT_PATH+"uploadfile"+Application.F+"images"+Application.F+shortfile.charAt(0)+Application.F+shortfile;
					File file=new File(filepath);
					if(!file.exists()) {
						FileUtils.writeByteArrayToFile(file, browser);
					}
					BaseService files = Application.getService("files");
					files.setData("img","articles",id,data.getTitle(),Application.APP_PATH+"uploadfile/images/"+shortfile.charAt(0)+"/"+shortfile,TimeUtils.getCurrentDateTime()).insert("type","file_type","file_type_id","name","original","created_at");
				} catch (IOException e) {
					
				} finally {
					CollctBase.removeAimg();
				}			
			}
			setMsg(true, "采集成功");	
			return true;
		}else {
			setMsg(false, "没有找到相关数据");
			return false;
		}			
	}
}
